package jinyilw.swing.visuals.Jcomp;

import jinyilw.common.Operator;
import jinyilw.swing.SystemTools;
import jinyilw.swing.graphics.GraphicsTools;
import jinyilw.swing.icon.LazyScaleIcon;
import jinyilw.swing.res.LoadClass;
import jinyilw.swing.rlaf.utils.RBorderFactory.SimpleRoundBorder;

import java.awt.Graphics;
import java.io.File;
import java.util.ArrayList;

public class AddFileComp extends JImageTextComp
{
	private static final long serialVersionUID = 2663756377634445446L;
	private static final LazyScaleIcon addFileImage = LazyScaleIcon
			.getIcon(LoadClass.class, "addFile.png");
	public static final LazyScaleIcon fileImage = LazyScaleIcon
			.getIcon(LoadClass.class, "file.png");
	private final SimpleRoundBorder roundBorder = new SimpleRoundBorder(
			GraphicsTools.getDottedStroke());
	private volatile ArrayList<Operator<Object>> dropOperators;
	private File file;

	public AddFileComp()
	{
		setImage(addFileImage);
		setText("单击或拖放添加文件");
		setBorder(roundBorder);
		setRolloverEnable(true);
	}

	public void reset()
	{
		file = null;
		setImage(addFileImage);
		setText("单击或拖放添加文件");
	}

	public void setFile(File f)
	{
		if (f == null || f == file)
			return;
		file = f;
		setImage(fileImage);
		setText(f.getAbsolutePath());
	}

	public File getFile()
	{
		return file;
	}

	private synchronized void createDropOperators()
	{
		if (dropOperators == null)
		{
			dropOperators = new ArrayList<>();
			SystemTools.makeDropTarget(this, o -> {
				for (Operator<Object> operator : dropOperators)
					operator.operate(o);
			});
		}
	}

	public void addDropOperator(Operator<Object> operator)
	{
		if (dropOperators == null)
			createDropOperators();
		dropOperators.add(operator);
	}

	@Override
	public void paint(Graphics g)
	{
		roundBorder.setActivated(isRollover);
		super.paint(g);
	}

}
